<template>
	<view style="padding-bottom: 130rpx;">
		<uni-forms>


			<uni-section title="订单信息" type="line">
				<view class="formInfo">
					<uni-forms-item label="更换车辆" labelWidth="auto">
						<view @click="chooseChangeCar">
							<u--input v-model="changeCarInfo.carNo" placeholder="请选择车辆" disabled disabledColor="#fff"
								suffixIcon="arrow-right"></u--input>
						</view>
					</uni-forms-item>
					<uni-forms-item label="是否自定义新订单编号" labelWidth="auto">
						<view class="flex-row-center" style="position: relative;top: 16rpx;">
							<text style="margin-right:10rpx;">否</text>
							<u-switch v-model="isCustomOrder" size="15" activeColor="#2879FF"
								@change="myOrderNo = null"></u-switch>
							<text style="margin-left:10rpx;">是</text>
						</view>
					</uni-forms-item>
					<uni-forms-item v-if="isCustomOrder" label="自定义订单编号" labelWidth="auto">
						<u--input v-model="myOrderNo" placeholder="请输入自定义新订单编号"></u--input>
					</uni-forms-item>

					<template>
						<view class="textItem">
							<text>订单编号</text>
							<text style="color: #333;">{{ breachInfo.orderInfo.orderNo }}</text>
						</view>
						<view class="textItem">
							<text>预约租期</text>
							<text style="color: #333;">{{ leaseDays }}天</text>
						</view>
						<view class="textItem">
							<text>已用租期</text>
							<text style="color: #333;">{{ useDays }}天</text>
						</view>
						<view class="textItem">
							<text>剩余租期</text>
							<text style="color: #333;">{{ residueDays }}天</text>
						</view>
						<view class="textItem">
							<text>当前车型</text>
							<text style="color: #333;">{{ breachInfo.orderInfo.modelName }}</text>
						</view>
						<view class="textItem">
							<text>当前车辆</text>
							<text style="color: #333;">{{ form.carNo }}</text>
						</view>
						<view class="textItem">
							<text>交车时间</text>
							<text style="color: #333;">{{ breachInfo.orderInfo.actualStartTime }}</text>
						</view>
						<view class="textItem">
							<text>换车时间</text>
							<text style="color: #333;">{{ form.takeAlsoTime }}</text>
						</view>
						<template v-if="changeCarInfo.carId">
							<view class="textItem">
								<text>换车车型</text>
								<text style="color: #333;">{{ changeCarInfo.carInfo }}</text>
							</view>
							<view class="textItem">
								<text>更换车辆</text>
								<text style="color: #333;">{{ changeCarInfo.carNo }}</text>
							</view>
						</template>
					</template>
				</view>
			</uni-section>

			<template v-if="tableData.length > 0">
				<uni-section title="原车费用信息" type="line">
					<view class="formInfo">
						<view v-for="(item, index) in breachInfo.rentItems" :key="index" style="margin: 20rpx; 0">
							<view class="flex-row-center-sb" style="margin-bottom: 20rpx;">
								<text style="font-size: 28rpx;color: #666;">{{ item.chargeProjectName }}</text>
								<!-- 		<block v-if="index == 0">
								<text style="font-size: 26rpx;color: #2879FF;" @click.stop="showRentDetail = !showRentDetail">明细</text>
							</block> -->
							</view>
							<uni-table ref="table" :loading="loading" border stripe>
								<uni-tr>
									<uni-th width="70" align="center"><text style="color: #2879FF;">单价</text></uni-th>
									<uni-th width="70" align="center"><text style="color: #2879FF;">数目</text></uni-th>
									<uni-th width="70" align="center"><text style="color: #2879FF;">费用</text></uni-th>
									<uni-th width="90" align="center"><text
											style="color: #2879FF;">已使用费用</text></uni-th>
								</uni-tr>
								<uni-tr>
									<uni-td
										align="center">{{ item.unitPrice }}{{ item.chargeItemsType | chargeItemsType }}</uni-td>
									<uni-td align="center">{{ item.number }}</uni-td>
									<uni-td align="center">{{ item.chargeMoney }}</uni-td>
									<uni-td align="center">{{ item.usedMoney }}</uni-td>
								</uni-tr>
							</uni-table>
						</view>

					</view>
				</uni-section>

				<uni-section title="新车费用信息" type="line">
					<view class="formInfo">
						<view v-for="(item, index) in tableData" :key="index" style="margin: 20rpx; 0">
							<!-- 费用项标题及操作按钮 -->
							<view class="flex-row-center-sb" style="margin-bottom: 20rpx;">
								<text style="font-size: 28rpx;color: #666;">{{ item.chargeProjectName }}</text>

								<block v-if="item.isRent == 1">
									<text style="font-size: 26rpx;color: #2879FF;"
										@click.stop="showRentDetail = !showRentDetail">日租金明细</text>
								</block>
								<block v-else>
									<view class="flex-row" v-if="item.canEdit != 1">
										<u-switch v-if="item.isOptional == 1 && item.canEdit != 3"
											v-model="item.selected" size="20"></u-switch>
										<template v-if="item.canEdit == 3">
											<!-- 编辑按钮 -->
											<view style="margin-right: 20rpx;margin-left: 20rpx;"
												@click="editCostItem(2, index, item)">
												<u-icon name="edit-pen" color="#2879FF" size="24"></u-icon>
											</view>
											<!-- 删除按钮 -->
											<view @click="deleteCostItem(index)"><u-icon name="trash" color="#2879FF"
													size="24"></u-icon></view>
										</template>
									</view>
								</block>
							</view>

							<uni-table ref="table" :loading="loading" border stripe>
								<uni-tr>
									<uni-th width="100" align="center">
										<text
											style="color: #2879FF;">单价({{ item.chargeItemsType | chargeItemsType }})</text>
									</uni-th>
									<uni-th width="100" align="center"><text style="color: #2879FF;">数目</text></uni-th>
									<uni-th width="100" align="center"><text style="color: #2879FF;">费用</text></uni-th>
								</uni-tr>
								<uni-tr>
									<uni-td align="center">
										<template>
											<u--input v-model="item.unitPrice" @input="check" type="digit"
												placeholder="请输入单价"></u--input>
										</template>
									</uni-td>
									<uni-td align="center" v-if="item.canEdit == 2">
										<!-- 按天不可编辑 -->
										<template v-if="item.chargeItemsType == 2">
											{{ item.number }}
										</template>
										<!-- 按次/按个可编辑 -->
										<template v-else>
											<!-- 无上限 -->
											<u-number-box v-if="item.upperLimitOfNumber && item.upperLimitOfNumber > 0"
												integer :min="0" :max="item.upperLimitOfNumber"
												v-model="item.number"></u-number-box>
											<!-- 有上限 -->
											<u-number-box v-else integer :min="0" v-model="item.number"></u-number-box>
										</template>
									</uni-td>
									<uni-td v-else align="center">{{ item.number }}</uni-td>

									<uni-td align="center">{{ item.chargeMoney }}</uni-td>
								</uni-tr>
							</uni-table>
						</view>

						<view class="flex-xy-center">
							<view class="flex-row-center addCost" @click="editCostItem(1)">
								<u-icon name="plus-circle" color="#fff"></u-icon>
								<text style="color: #fff;font-size: 26rpx;margin-left: 20rpx;">添加收费项</text>
							</view>
						</view>
					</view>
				</uni-section>

				<uni-section title="退款/补缴费用" type="line">
					<view class="formInfo">
						<uni-forms ref="form">

							<uni-forms-item label="已用租金">
								<view>
									<u--input v-model="usedRent" placeholder="请输入已用租金" type="digit"
										@input="checkUseRent"></u--input>
								</view>
							</uni-forms-item>
							<view class="textItem">
								<text>剩余租金</text>
								<text style="color: #333;">{{ residueRent}}元</text>
							</view>
							<view class="textItem">
								<text>原租金总额</text>
								<text style="color: #333;">{{ orderTotalCost}}元</text>
							</view>

							<view class="textItem">
								<text>新车租金</text>
								<text style="color: #333;">{{ changeCarTotalCost || 0 }}元</text>
							</view>
							<view class="textItem">
								<text>现租金总额</text>
								<text style="color: #333;">{{nowTotalCost}}元</text>
							</view>

						</uni-forms>
					</view>
				</uni-section>
			</template>



			<view class="bottomView flex-row-center-sb">
				<view class="btn" style="border: 1rpx solid #1673ff;color: #1673ff;background-color: #fff;"
					@click="lastStep">上一步</view>
				<view class="btn" @click="confimChangeCar">确认换车</view>
			</view>

			<!-- 新增收费项弹框 -->
			<u-popup :show="showEditCost" mode="bottom" @close="showEditCost = false" closeable round="12">
				<view class="flex-colum-center" style="padding: 40rpx 24rpx 20rpx;">
					<view style="margin-bottom: 30rpx;">{{ popTitleType == 1 ? '新增' : '编辑' }}收费项</view>
					<uni-forms ref="form">
						<uni-forms-item label="收费项名称" labelWidth="90" required>
							<view><u--input v-model="customCost.chargeProjectName" placeholder="请输入收费项名称"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="收费类型" required>
							<uni-data-checkbox v-model="customCost.chargeItemsType" :localdata="chargeItemsTypes"
								@change="changeType" />
						</uni-forms-item>

						<uni-forms-item label="单价" type="number" labelWidth="90" required>
							<view>
								<u--input v-model="customCost.unitPrice" @input="check" type="digit"
									placeholder="请输入单价"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="数目" labelWidth="90" required>
							<view>
								<u--input v-model="customCost.number" type="number"
									:disabled="customCost.chargeItemsType == 2 ? true : false"
									placeholder="请输入数量"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="费用合计" labelWidth="90">
							<view>
								<text
									style="position: relative;top: 15rpx;">{{ customCost.number * customCost.unitPrice || '0' }}</text>
							</view>
						</uni-forms-item>
					</uni-forms>

					<view class="commitBtn" @click="commitCost">提交</view>
				</view>
			</u-popup>

			<u-popup :show="showRentDetail" mode="center" @close="showRentDetail = false" closeable round="12">
				<view class="flex-colum-center" style="padding: 40rpx 24rpx">
					<view style="margin-bottom: 30rpx;">租赁费明细</view>
					<scroll-view scroll-y="true">
						<view style="max-height: 800rpx;">
							<view class="flex-row-center-sb payCostItem"
								v-for="(item, index) in changeCarFee.planPriceVoList" :key="index">
								<text>{{ item.time }}</text>
								<text>{{ item.price }}元</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</u-popup>
		</uni-forms>
	</view>
</template>

<script>
	import * as api from '@/api/order-api.js';
	export default {
		data() {
			return {
				showEditCost: false,
				chargeItemsTypes: [{
						value: 1,
						text: '按次'
					},
					{
						value: 2,
						text: '按天'
					},
					{
						value: 6,
						text: '按个'
					}
				],
				currentEditCostIndex: -1,
				customCost: {
					chargeProjectName: '',
					chargeMoney: '',
					chargeItemsType: 1,
					canEdit: 3,
					isRent: 2,
					number: '',
					unitPrice: '',
					calculate: '',
					isOptional: 1,
					selected: true,
					chargeItemsId: null,
					chargeProjectCategory: 9,
					originalPrice: null
				},
				showRentDetail: false,
				form: {},
				liquidatedDamages: {},
				breachInfo: {
					orderInfo: {
						leaseDays: 0
					},
					liquidatedDamages: {
						days: 0
					}
				},
				changeCarInfo: {
					carNo: ''
				},
				changeCarFee: {},
				tableData: [],
				usedRent: 0, //已用租金,
				isCustomOrder: false,
				myOrderNo: null,

			};
		},
		computed: {
			refundAmount() {
				var amount = 0;
				if (!uni.$u.test.isEmpty(this.liquidatedDamages)) {
					amount = this.liquidatedDamages.rent - this.liquidatedDamages.damages;
				}
				return amount;
			},
			// 原车辆费用总计
			orderTotalCost() {
				const costs = this.breachInfo.rentItems || [];
				let total = 0;
				costs.forEach((item) => {
					total += item.chargeMoney;
				})
				return total;

			},
			// 原车辆剩余租金=原车辆费用总计-已用租金
			residueRent() {
				return this.orderTotalCost - this.usedRent;
			},
			//预约天数
			leaseDays() {
				return this.breachInfo.orderInfo.leaseDays || 0;
			},
			//已用天数
			useDays() {
				return this.breachInfo.liquidatedDamages.days || 0;
			},
			//剩余天数
			residueDays() {
				const residueDays = this.leaseDays - this.useDays;
				return residueDays;
			},

			// 换车车辆总费用
			changeCarTotalCost() {
				var total = 0;
				if (this.tableData.length > 0) {
					this.tableData.map(item => {
						item.selected = item.selected;
						//可编辑
						if (item.canEdit != 1) {
							if (item.chargeItemsType == 2) {
								//按天->开关,无上限限制
								item.chargeMoney = item.number * item.unitPrice;
								item.calculate = item.unitPrice + '×' + item.number;
								return item;
							} else {
								////按次|按个->步进器->有最大金额限制
								if (item.number > 0) {
									//当次数|个数大于0时
									const itemCost = item.number * item.unitPrice; //计算出来的金额
									if (item.upperLimitOfAmount != -1) {
										//金额有上限
										if (itemCost > item.upperLimitOfAmount) {
											//当金额大于最大限制金额->取最大金额
											item.chargeMoney = item.upperLimitOfAmount;
											item.calculate = item.unitPrice + '×️' + item.number;
											return item;
										} else {
											//当在最大金额范围内
											item.chargeMoney = item.number * item.unitPrice;
											item.calculate = item.unitPrice + '×' + item.number;
											return item;
										}
									} else {
										//金额无上限
										item.chargeMoney = item.number * item.unitPrice;
										item.calculate = item.unitPrice + '×' + item.number;
										return item;
									}
								} else {
									item.chargeMoney = item.number * item.unitPrice;
									item.calculate = item.unitPrice + '×' + item.number;
									return item;
								}
							}
						} else {
							item.chargeMoney = item.number * item.unitPrice;
							item.calculate = item.unitPrice + '×' + item.number;
							return item;
						}
					});
					this.tableData.map(item => {
						if (item.selected) {
							// console.log('当前收费项金额', item.chargeMoney,'---收费项名称', item.chargeProjectName);
							total += item.chargeMoney;
							// console.log('总金额', total);
						}
					});
				}

				console.log('费用项', this.tableData);
				return total;
			},
			// 现租金总额(已用租金+新车车辆租金)
			nowTotalCost() {
				return Number(this.usedRent) + Number(this.changeCarTotalCost);
			}
		},
		onLoad(op) {
			this.form = JSON.parse(decodeURIComponent(op.form));
			this.getEarlyReturnDetail();
		},
		methods: {
			// 选择更换车辆
			chooseChangeCar() {
				uni.navigateTo({
					url: `./orderChangeCarList?orderNo=${this.form.orderNo}`
				});
				uni.$once('changeCar', carInfo => {
					this.changeCarInfo = carInfo;
					this.getChangeFee();
				});
			},
			//获取换车车辆信息
			getChangeFee() {
				api.changeFee({
					carId: this.changeCarInfo.carId,
					days: this.residueDays,
					orderNo: this.form.orderNo,
					takeAlsoTime: this.form.takeAlsoTime
				}).then(res => {
					this.changeCarFee = res.data;
					if (!uni.$u.test.isEmpty(this.changeCarFee.chargingItemsVoList)) {
						this.changeCarFee.chargingItemsVoList.map(item => {
							return this.$set(item, 'selected', true);
						});
					}
					if (!uni.$u.test.isEmpty(this.changeCarFee.requiredInsurance)) {
						this.changeCarFee.requiredInsurance.map(item => {
							return this.$set(item, 'selected', true);
						});
					}
					if (!uni.$u.test.isEmpty(this.changeCarFee.noRequiredInsurance)) {
						this.changeCarFee.noRequiredInsurance.map(item => {
							return this.$set(item, 'selected', false);
						});
					}
					if (!uni.$u.test.isEmpty(this.changeCarFee.noMandatoryOtherCostList)) {
						this.changeCarFee.noMandatoryOtherCostList.map(item => {
							if (item.canEdit == 2) {
								if (item.chargeItemsType != 2) {
									item.number = 1
								}
							}

							this.$set(item, 'selected', false)
						});
					}
					this.tableData = [
						...(this.changeCarFee.chargingItemsVoList || []),
						...(this.changeCarFee.requiredInsurance || []),
						...(this.changeCarFee.noRequiredInsurance || []),
						...(this.changeCarFee.noMandatoryOtherCostList || [])
					];
				});
			},
			//获取提前还车扣款明细
			getEarlyReturnDetail() {
				api.earlyReturnDetail({
					orderNo: this.form.orderNo,
					takeAlsoTime: this.form.takeAlsoTime,
					type: 4
				}).then(res => {
					this.breachInfo = res.data;
					this.liquidatedDamages = res.data.liquidatedDamages;
					this.usedRent = this.breachInfo.usedRent;
				});
			},

			// 上一步
			lastStep() {
				uni.navigateBack();
			},
			// 确认换车
			confimChangeCar() {

				if (uni.$u.test.isEmpty(this.changeCarInfo.carNo)) {
					this.$u.toast('请选择换车车辆');
					return
				} else {
					uni.showLoading({
						title: '换车中...',
						mask: true
					});
					let chargeItemsVo = this.tableData.filter(item => {
						return item.selected == true && item.chargeMoney != 0;
					});

					let param = {
						...this.form,
						usedRent: this.usedRent,
						oldRent: this.orderTotalCost,
						rentTotal: this.changeCarTotalCost,
						newRent: this.nowTotalCost,
						leaseDays: this.residueDays,
						planId: this.changeCarFee.planId,
						modelInfo: this.changeCarFee.modelName,
						modelId: this.changeCarFee.modelId,
						carId: this.changeCarInfo.carId,
						carNo: this.changeCarInfo.carNo,
						planPriceVoList: this.changeCarFee.planPriceVoList || [],
						chargeItemsVo: chargeItemsVo,
						myOrderNo: this.myOrderNo,
						rentItems: this.breachInfo.rentItems
					};

					api.changeCar(param).then(data => {
						uni.$emit('refreshOrder');
						this.$u.toast('换车成功');
						uni.navigateBack({
							animationDuration: 300,
							delta: 2
						});
					}).finally(() => {
						uni.hideLoading();
					});
				}



			},
			deleteCostItem(index) {
				this.tableData.splice(index, 1);
			},

			// 添加或者编辑自定义费用项
			editCostItem(type, index, info) {
				this.popTitleType = type;
				if (type == 1) {
					//新增
					this.customCost = {
						chargeProjectName: '',
						chargeMoney: '',
						chargeItemsType: 1,
						canEdit: 3,
						isRent: 2,
						number: '',
						unitPrice: '',
						calculate: '',
						isOptional: 1,
						selected: true,
						chargeItemsId: null,
						chargeProjectCategory: 9,
						originalPrice: null
					};
				} else {
					//编辑
					this.customCost = info;
					this.currentEditCostIndex = index;
				}
				this.showEditCost = true;
			},
			changeType(e) {
				console.log(e);
				if (e.detail.value == 2) {
					this.customCost.number = this.fromData.leaseDays;
				}
			},
			//确定提交费用项
			commitCost() {
				if (uni.$u.test.isEmpty(this.customCost.chargeProjectName)) {
					uni.$u.toast('请输入费用项名称');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.unitPrice)) {
					uni.$u.toast('请输入单价');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.number)) {
					uni.$u.toast('请输入数目');
					return;
				} else if (this.customCost.number == '0') {
					uni.$u.toast('数目不能为0,请重新输入');
					return;
				} else {
					//新增
					this.tableData.push(this.customCost);
					this.showEditCost = false;
				}
			},
			check(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.customCost.unitPrice = e;
				});
			},
			checkUseRent(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				let useRent = parseFloat(e);
				if (useRent > this.orderTotalCost) {
					e = this.orderTotalCost;
				}
				this.$nextTick(() => {
					this.usedRent = e;
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.formInfo {
		margin: 20rpx;
		padding: 20rpx 30rpx;
		background: #ffffff;
		border-radius: 18rpx;
		background: #ffffff;
		box-shadow: 0px 4rpx 16rpx 0px rgba(1, 10, 18, 0.1);
		border-radius: 16rpx;
	}

	.bottomView {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		padding: 0 44rpx;

		.btn {
			height: 88rpx;
			width: 312rpx;
			line-height: 88rpx;
			text-align: center;
			border-radius: 44rpx;
			background-color: #1673ff;
			font-size: 32rpx;
			color: #fff;
		}
	}

	.textItem {
		padding: 12rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 28rpx;
		color: #666;
	}

	.payCostItem {
		height: 80rpx;
		width: 600rpx;
		border-bottom: 1rpx solid #ededed;
		font-size: 28rpx;
		color: #333;
	}

	.addCost {
		margin: 32rpx 0;
		box-sizing: border-box;
		padding-left: 30rpx;
		width: 242rpx;
		height: 60rpx;
		background: #1673ff;
		border-radius: 30rpx;
	}

	.commitBtn {
		background-color: #1673ff;
		border-radius: 12rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		width: 300rpx;
		margin-top: 30rpx;
	}
</style>